package com.vast.vastlcd.lcdAPI;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.eclipse.ui.PlatformUI;

/**
 * 
 */
public class LCDMessageHeader {
	
	public static int LCD_SETTITLE_REQ = 1;
	public static int LCD_SETPOSITION_REQ = 2;
	public static int LCD_SETSIZE_REQ = 3;
	public static int LCD_SETPIXELS_REQ = 4;
	public static int LCD_SETIMAGE_REQ = 5;
	
	public static int LCD_REQ_MAX = 6;
	
	public static int LCD_MSG_HDR_BYTE_SIZE = 8;
	
	public int nMessageLength;
	public int nMessageType;
	
	/**
	 * @return
	 */
	public byte[] javaToNative () {
	 	if (this == null) 
	 		return null;
	 	
	 	byte[] buffer = null;
		try {
			// write data to a byte array and then ask super to convert to pMedium
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			LCDDataOutputStream writeOut = new LCDDataOutputStream(out);
			
			writeOut.writeLSBInt(nMessageLength);
			writeOut.writeLSBInt(nMessageType);
			
			buffer = out.toByteArray();
			writeOut.close();
			//return buffer;
			//super.javaToNative(buffer, transferData);
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	    return buffer;
	}
	
	/**
	 * @param buffer
	 * @return
	 */
	static public LCDMessageHeader nativeToJava(byte[] buffer){	
	 
 		if (buffer == null) 
 			return null;
 		
 		LCDMessageHeader msgHeader = new LCDMessageHeader();
 		try {
 			ByteArrayInputStream in = new ByteArrayInputStream(buffer);
 			LCDDataInputStream readIn = new LCDDataInputStream(in);
 			
 			msgHeader.nMessageLength = readIn.readLSBInt();
 			msgHeader.nMessageType = readIn.readLSBInt();
 			
 			readIn.close();
 		} catch (IOException ex) {
 			return null;
 		}
 		
 		return msgHeader; 		
	}
	 
	/**
	 * @param messageBodyBuffer
	 */
	public void ProcessMessageHeader(byte[] messageBodyBuffer) {
		// Before processing the message confirm the UI is OK to update
		while (!PlatformUI.isWorkbenchRunning())
			;
		 
	 	if (nMessageType == LCD_SETTITLE_REQ)  
	 		LCDSetTitleRequest.processMessage(messageBodyBuffer);
	 	else if (nMessageType == LCD_SETPOSITION_REQ)  
	 		LCDSetPositionRequest.processMessage(messageBodyBuffer);
	 	else if (nMessageType == LCD_SETSIZE_REQ)  
	 		LCDSetSizeRequest.processMessage(messageBodyBuffer);
	 	else if (nMessageType == LCD_SETPIXELS_REQ)  
	 		LCDSetPixelsRequest.processMessage(messageBodyBuffer);
	 	else if (nMessageType == LCD_SETIMAGE_REQ)  
	 		LCDSetImageRequest.processMessage(messageBodyBuffer);
	 	else
	 		System.out.println("Unknown message type: " + nMessageType);		 
	}
}

